/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.service.topo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sinodata.bsm.center.bean.Condition;
import com.sinodata.bsm.center.bean.Page;
import com.sinodata.bsm.center.bean.RelationHelper;
import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.cache.ResCache;
import com.sinodata.bsm.center.cache.ResTypeCache;
import com.sinodata.bsm.center.service.relation.ResRelationService;
import com.sinodata.bsm.center.service.resource.ResService;
import com.sinodata.bsm.common.vo.RelationType;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.common.vo.ResRelation;
import com.sinodata.bsm.common.vo.TopuConf;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author sunxiangxue
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-10-10 下午5:11:38          sunxiangxue        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
@Component("topoBlazeDSImpl")
public class TopoBlazeDSService {

    Logger logger = Logger.getLogger(TopoBlazeDSService.class);

    @Autowired
    private TopoService topoService;
    @Autowired
    private ResService resService;
    @Autowired
    private ResRelationService resRelationService;
    @Autowired
    private ResCache resCache;
    @Autowired
    private ResTypeCache resTypeCache;
    private com.sinodata.bsm.center.bean.Page<Res> page;

    /**
     * 通过资源ID查询该资源及其子资源事件集合
     * @return
     */
    public String findResEventsByResId(Long[] resourceIds) {
        if (resourceIds == null || resourceIds.length < 1)
            return (new JSONArray()).toString();
        JSONArray jsonArray = new JSONArray();
        jsonArray = topoService.findResEventsByResId(resourceIds);
        return jsonArray.toString();
    }

    /**
     * 查询首页播放列表
     * @return
     */
    public String findShowTopos() {
        JSONArray jsonArray = new JSONArray();
        try {
            jsonArray = topoService.findShowTopos();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonArray.toString();
    }

    /**
     * 通过拓扑ID查询拓扑
     * @param topoId 拓扑ID
     * @return
     */
    public String findTopoById(Long topoId) {
        logger.debug("topoid=:----" + topoId);
        TopuConf topuConf = topoService.findById(topoId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.element("xml", topuConf.getXml());
        return jsonObject.toString();
    }

    /**
     * 查询资源
     * @param list 查询条件。list集合方式存储，每个元素以key=value方式存储。
     * @param pageSize 每页显示数量（目前未分页，显示2000条）
     * @param start 起始序列，分页对象使用（前台默认传1）
     * @return
     * @throws Exception
     */
    public String searchResource(List<String> list, int pageSize, int start) throws Exception {
        if (list == null)
            return "";
        page = new Page<Res>();
        /* 查询条件准备*/
        Map<String, String> newParameter = new HashMap<String, String>();
        for (String param : list) {
            String[] keyValue = param.split("\\=");
            if (keyValue == null || keyValue.length < 2)
                continue;
            newParameter.put(keyValue[0], keyValue[1]);
        }
        Condition condition = new Condition();
        condition.setWhere(newParameter);
        int pageno = (start / pageSize) + 1;
        page.setPageNo(pageno);
        page.setPageSize(pageSize);
        /* 查询资源*/
        List<Res> res = resService.findByPage(page, condition);
        /* 响应数据处理*/
        JSONArray array = new JSONArray();
        int index = 0;
        for (Res r : res) {
            JSONObject json = new JSONObject();
            json.element("id", r.getId());//资源ID
            json.element("ip", r.getIp() == null ? "" : r.getIp());//资源IP
            json.element("name", r.getName());//资源名称
            json.element("resTypeId", r.getResTypeId());//资源类别ID
            //和该资源相关的资源信息及关系信息。
            json.element("relationInfo", findResRelation(r.getId()).toString());
            /* 显示的资源名称，格式为：父资源名称/资源名称*/
            Res parent = null;
            List<ResBean> resBeans = RelationHelper.parents(r.getId());
            if (resBeans.size() > 0) {
                parent = resBeans.get(0).res();
            }
            StringBuffer parentNameValue = new StringBuffer("");
            parentNameValue.append(parent == null ? "" : parent.getName() + "/");
            parentNameValue.append(r.getName() == null ? "" : r.getName());
            json.element("parentName", parentNameValue.toString());
            array.add(json);
            /*只向前台传送与pageSize相等条数的记录，pageSize目前默认为2000条*/
            if (index > pageSize)
                break;
            else
                index++;
        }
        JSONObject object = new JSONObject();
        object.element("iTotalRecords", page.getTotal());
        object.element("aaData", array);
        return object.toString();
    }

    /**
     * 查询与某一资源有关系的所有资源信息及关系信息。
     * @param resId 某资源ID
     * @return
     */
    private JSONObject findResRelation(Long resId) {
        JSONArray jsonArray = new JSONArray();
        //查询资源关系
        List<ResRelation> relList = resRelationService.getResRelationsOfRes(resId);
        JSONObject json = new JSONObject();
        jsonArray = new JSONArray();
        if (relList == null)
            return json;
        //包装数据
        for (ResRelation rel : relList) {
            Long childResId = null;
            // 查询子资源
            if (resId.equals(rel.getStartId())) {
                childResId = rel.getEndId();
            }
            // 查询父资源
            else if (resId.equals(rel.getEndId())) {
                childResId = rel.getStartId();
            }
            Res cRes = resService.get(childResId.longValue());
            if (cRes == null) {
                continue;
            }
            JSONObject cjson = new JSONObject();
            cjson.element("resId", cRes.getId());//资源ID
            RelationType type = resRelationService.findRelationTypeById(rel.getRelationTypeId());
            cjson.element("relTypeId", type.getId());//关系类型ID
            cjson.element("relTypeName", type.getName());//关系类型名称
            cjson.element("relationLabel", rel.getLabel());//关系显示名称
            jsonArray.add(cjson);
        }
        json.element("children", jsonArray);
        return json;
    }

    /**
     * 查询资源tooltip信息。
     * @param resId 资源id
     * @return
     */
    public String findToolTipInfo(Long resId) {
        JSONObject obj = new JSONObject();
        Res res = resCache.get(resId);
        if (res == null)
            return obj.toString();
        obj.element("id", res.getId());
        obj.element("name", res.getName());
        obj.element("typeName", resTypeCache.get(res.getResTypeId()).getName());
        obj.element("ip", res.getIp());
        obj.element("healthDegree", res.getHealthDegree());
        return obj.toString();
    }
}
